import { ref, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { useExamStore } from '@/stores/modules/exam-student'
import { submitExam } from '@/api/student/exam'

/**
 * 考试计时相关功能
 * @param {Boolean} autoSubmit 是否自动提交
 * @returns {Object} 计时器相关方法
 */
export function useExamTimer(autoSubmit = true) {
  const router = useRouter()
  const examStore = useExamStore()
  
  // 计时器间隔标识
  const timerInterval = ref(null)
  // 上次同步时间标识
  const syncInterval = ref(null)
  // 考试结束标识
  const isExamEnded = ref(false)
  
  /**
   * 启动计时器
   */
  const startTimer = () => {
    if (timerInterval.value) return
    
    // 每秒钟更新倒计时
    timerInterval.value = setInterval(() => {
       
      const remaining = examStore?.remainingTime - 1
      examStore.updateRemainingTime(remaining)
      
      // 当剩余时间小于等于0，结束考试
      if (remaining <= 0) {
        endExam()
      } 
      // 倒计时提醒
      else if (remaining === 300) { // 5分钟
        ElMessage.warning('考试还剩5分钟，请抓紧时间作答')
      } else if (remaining === 60) { // 1分钟
        ElMessage.warning('考试还剩1分钟，即将自动交卷')
      }
    }, 1000)
    
    // 每30秒自动同步答案
    syncInterval.value = setInterval(() => {
      examStore.syncAnswers()
    }, 100000)
  }
  
  /**
   * 停止计时器
   */
  const stopTimer = () => {
    if (timerInterval.value) {
      clearInterval(timerInterval.value)
      timerInterval.value = null
    }
    
    if (syncInterval.value) {
      clearInterval(syncInterval.value)
      syncInterval.value = null
    }
  }
  
  /**
   * 结束考试
   */
  const endExam = async () => {
    if (isExamEnded.value) return
    isExamEnded.value = true
    
    // 停止计时器
    stopTimer()
    
    // 最后一次同步答案
    await examStore.syncAnswers()
    
    if (autoSubmit) {
      // 自动提交试卷
      try {
        await ElMessageBox.alert(
          '考试时间已结束，系统将自动提交您的试卷',
          '提示',
          {
            type: 'warning',
            showClose: false,
            confirmButtonText: '确定'
          }
        )
        
        await submitExam(examStore.currentExam.id, {
          autoSubmit: true,
          studentPaperId: examStore.currentExam.studentPaperId
        })
        
        // 跳转到成绩页面
        router.push(`/score/${examStore.currentExam.id}`)
      } catch (error) {
        console.error('自动提交失败:', error)
        ElMessage.error('自动提交失败，请手动提交试卷')
      }
    }
  }
  
  /**
   * 格式化时间为 HH:MM:SS
   * @param {Number} seconds 剩余秒数
   * @returns {String} 格式化后的时间
   */
  const formatTime = (seconds) => {
    const hours = Math.floor(seconds / 3600)
    const minutes = Math.floor((seconds % 3600) / 60)
    const secs = seconds % 60
    
    return [
      hours.toString().padStart(2, '0'),
      minutes.toString().padStart(2, '0'),
      secs.toString().padStart(2, '0')
    ].join(':')
  }
  
  onMounted(() => {
    startTimer()
  })
  
  onUnmounted(() => {
    stopTimer()
  })
  
  return {
    startTimer,
    stopTimer,
    endExam,
    formatTime,
    isExamEnded
  }
} 